package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.dto.DishDto;
import com.example.demo.entity.Dish;
import com.example.demo.entity.DishFlavor;
import com.example.demo.mapper.DishMapper;
import com.example.demo.service.DishFlavorService;
import com.example.demo.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
   @Autowired
    DishFlavorService dishFlavorService;
    //新增菜品同时保存对应的口味
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品的基本信息到菜品表
        super.save(dishDto);
        //保存菜品口味数据到菜品口味表dish_flavor
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        //保存菜品口味，把数据放入口味表dish_flavor
        dishFlavorService.saveBatch(flavors);
    }
//查询菜品及其口味
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        Dish byId = this.getById(id);
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> list = dishFlavorService.list(lambdaQueryWrapper);
        DishDto dishDto=new DishDto();
        BeanUtils.copyProperties(byId,dishDto);
        dishDto.setFlavors(list);
        return dishDto;
    }
    //根据id修改菜品信息和口味信息
    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //会根据相同的属性名字段自动匹配进去
        //修改菜品信息
        this.updateById(dishDto);
        //构造条件对象
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        //删除口味信息
        dishFlavorService.remove(lambdaQueryWrapper);
        //添加口味信息
        List<DishFlavor> flavors = dishDto.getFlavors();//因为flavors没有给dishID赋值
        //故要通过stream便利在每个字段添加值
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
    }
}
